package com.example.myapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.example.myapplication.R;

public class HomeActivity extends AppCompatActivity {
    private static final String TAG = "主页";
    private String mUsername;
    private Button btnLogout;
    private BottomNavigationView bottomNav;
    private UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate：我创建了哦！");
        setContentView(R.layout.activity_home);

        initViews();
        receiveUsername();
        setupLogoutListener();

        // 初始化ViewModel，同步用户名
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        if (mUsername != null) {
            userViewModel.updateUsername(mUsername);
        }

        // 初始化底部导航
        bottomNav = findViewById(R.id.bottom_nav);

        // 首次启动默认显示首页
        if (savedInstanceState == null) {
            replaceFragment(new HomeFragment());
        }

        // 底部导航切换逻辑（修正：启动ProfileEditActivity，传递用户名）
        bottomNav.setOnItemSelectedListener(item -> {
            if (item.getItemId() == R.id.menu_home) {
                replaceFragment(new HomeFragment());
                return true;
            } else if (item.getItemId() == R.id.menu_profile) {
                // 启动个人信息编辑页，并传递用户名
                Intent intent = new Intent(HomeActivity.this, ProfileEditActivity.class);
                intent.putExtra("username", mUsername);
                startActivity(intent);
                return true;
            }
            return false;
        });
    }

    // 生命周期日志（保持原有逻辑）
    @Override
    protected void onStart() { super.onStart(); Log.d(TAG, "onStart：我可见了哦！"); }

    @Override
    protected void onResume() { super.onResume(); Log.d(TAG, "onResume：我可交互了哦！"); }

    @Override
    protected void onPause() { super.onPause(); Log.d(TAG, "onPause：我不可交互了哦！"); }

    @Override
    protected void onStop() { super.onStop(); Log.d(TAG, "onStop：我不可见了哦！"); }

    @Override
    protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy：我销毁了哦！"); }

    // 接收新用户名（若登录后更新）
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "onNewIntent");
        String newUsername = intent.getStringExtra("username");
        if (newUsername != null && !newUsername.isEmpty()) {
            mUsername = newUsername;
            userViewModel.updateUsername(mUsername);
        }
    }

    // 初始化控件（仅保留存在的控件）
    private void initViews() {
        btnLogout = findViewById(R.id.btn_logout);
        bottomNav = findViewById(R.id.bottom_nav);
    }

    // 接收登录页传递的用户名
    private void receiveUsername() {
        mUsername = getIntent().getStringExtra("username");
    }

    // “退出登录”按钮逻辑
    private void setupLogoutListener() {
        btnLogout.setOnClickListener(v -> showLogoutConfirmationDialog());
    }

    // 退出登录弹窗
    private void showLogoutConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("确认退出")
                .setMessage("您确定要退出登录吗?")
                .setPositiveButton("确定", (dialog, which) -> {
                    Intent intent = new Intent(HomeActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                })
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show();
    }

    // Fragment切换方法（仅用于“首页”Fragment切换）
    private void replaceFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
    }

    // 提供底部导航引用（供Fragment使用）
    public BottomNavigationView getBottomNav() {
        return bottomNav;
    }
}